﻿namespace WpInsights.Core
{
    using System;

    public class Iterator
    {
        public static void Process(string excelFileName, EnvironmentSettings environmentSettings)
        {
            EnvironmentType environmentType = EnvironmentType.Prod;
            var stackTraceRecords = ExcelConvertor.GetStackTraceRecords(excelFileName);
            var operationsData = ExceptionEvent.GetDataItems(stackTraceRecords);

            foreach (var keyValuePair in operationsData.DataItemCollections)
            {
                var dataItems = keyValuePair;

                ApmStoreWebRequest request = new ApmStoreWebRequest(new Uri(environmentSettings.DataWriterUrl + "/EventData"), environmentSettings);
                Console.WriteLine(DateTime.Now.ToString() + ": Sending APM data items...");
                request.Send(dataItems);
            }

            foreach (var appName in operationsData.Applications)
            {
                SendHeartBeat(appName, environmentSettings);
            }
        }

        private static void SendHeartBeat(string applicationName, EnvironmentSettings environmentSettings)
        {
            string data = ResourceReader.ReadToEnd(@"PCounterEventTemplatesOnline.xml");
            data = data.Replace("{UtcLogDate}", DateTime.UtcNow.ToString("s"));
            data = data.Replace("{EventSource}", applicationName);
            ApmStoreWebRequest request = new ApmStoreWebRequest(new Uri(environmentSettings.DataWriterUrl + "/PerformanceCounterData"), environmentSettings);
            Console.WriteLine(DateTime.Now.ToString() + ": Sending heartbeat event...");
            request.Send(data);
        }
    }

    public enum EnvironmentType
    {
        Local,
        Int,
        Prod
    }
}
